'''
Created on Nov 30, 2011

@author: stelios
'''

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy
import base64 
import StringIO
import urllib

class Matplotlib_plots:
    """
    Contains the methods that allow the creation of matplotlib scatter or histogram plots.
    
    """
    
    
    def __init__(self):
        """
        Initialize class. Temporarily using a placeholder variable for future use
        @param self : self
        """
        self.scatter = 1
        
        
    def get_xy_values_for_hist(self, x_data, x_bins=10):
        """
        Generate the X and Y data values for a histogram, based on a given number of bins
        
        @param x_data: The x axis data values
        @param x_bins : The number of bins based on which the data columns will be generated. Defaults to: 10
        @return: An array of x,y points for use by a histogram
        """
        x = numpy.array(x_data)
        n, bins, patches = plt.hist(x,bins = x_bins,histtype='bar')
        new = []
        counter = 0
        plt.clf()
        n = n.tolist()
        bins = bins.tolist()
        for val in n :
            new.append([bins[counter],val])
            counter  = counter + 1
        return new    
        
        
    def generate_plot(self,data, x_label="", y_label="", plot_type="Scatter", x_bins=10):
        """
        Generate a plot using Matplotlib. Type of plot can be either a Scatter plot or a Histogram.
        Returns the image as a png, encoded in base64 inline html using the img tag
        @param data: The data to plot. Must be a 2d array of X values and Y values for a Scatterplot, or an array of X values for a Histogram
        @param x_label : A string for the X label
        @param y_label : A string for the Y label
        @param plot_type : Should be either 'Scatter' or defaults to Histogram
        @param x_bins : The number of bins to separate the X values in for the Histogram

        @return: A String: The png img HTML tag
        """
        # definitions for the axes
        left, width = 0.1, 0.65
        bottom, height = 0.1, 0.65
        rect_scatter = [left, bottom, width, height]
    
        if plot_type == "Scatter":
            x = numpy.array(data[0])
            y = numpy.array(data[1])            
            
            # start with a rectangular Figure
            plt.figure(1, figsize=(8,8))
            axScatter = plt.axes(rect_scatter)     
            plt.ticklabel_format(style='sci', scilimits=(100000,100000))

            # the scatter plot:
            axScatter.scatter(x, y,c='c', marker='o', s=1)      
            plt.ylabel(y_label)

        else:
            x = numpy.array(data)
            #plt.ticklabel_format(style='sci', scilimits=(100000,100000))
            n, bins, patches = plt.hist(x, bins = x_bins, histtype='bar')
            plt.ylabel("Frequency")      
            #plt.axis(rect_scatter)

        imgdata = StringIO.StringIO()
        plt.xlabel(x_label)
        plt.grid(True)
        plt.savefig(imgdata, format='png', bbox_inches='tight', pad_inches=0.5)
        imgdata.seek(0)  # rewind the data
        uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(imgdata.buf))
        content = '<img src = "%s"/>' % uri
        plt.clf()
        return content
